package org.game.gobang.client.support;

import javafx.application.Platform;
import javafx.scene.control.Button;
import org.game.gobang.client.constant.ClientConstant;
import org.game.model.Click;
import org.game.result.RestResult;
import org.game.result.RestResultBuilder;
import org.game.result.ResultCode;
import org.game.util.JsonUtil;

public class GobangButton extends Button {
    private int width;
    private int height;
    private int pos;

    private boolean isClicked = false;

    private String color = "#f9d3e3";

    public GobangButton(int width, int height, int pos) {
        this.width = width;
        this.height = height;
        this.pos = pos;

        setMinWidth(width);
        setMinHeight(height);
        setStyle("-fx-background-color: #f9d3e3;");

        setOnAction((action) -> {
            if (this.isClicked) {
                return;
            }

            if (ClientConstant.canClick) {
                return;
            }

            ClientConstant.canClick = true;
            this.isClicked = true;

            RestResult restResult = new RestResultBuilder().success(ResultCode.CLICK);
            restResult.setData(Click
                    .builder()
                    .color(ClientConstant.clickedColor)
                    .pos(String.valueOf(pos))
                    .player(ClientConstant.player)
                    .build());
            ClientConstant.ctx.writeAndFlush(JsonUtil.toJson(restResult));

            this.setStyle("-fx-background-color: " + ClientConstant.clickedColor);
            color = ClientConstant.clickedColor;

            ClientConstant.win();
        });
    }

    public void changeColor(String color) {
        this.isClicked = true;
        this.setStyle("-fx-background-color: " + color);
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}
